import React from "react";
import { useState, useEffect, useRef } from "react";
import { useNavigate,useParams } from "react-router-dom";
import { PageHeader, Steps, Button, Form, Input, Select, message,notification } from "antd";
import NewsEditor from "../../../components/news-manage/NewsEditor";

import "./Newadd.css";
import axios from "axios";

export default function NewsUpdate(props) {
  const { Step } = Steps;
  const { Option } = Select;
  const [current, setcurrent] = useState(0);
  const [categoryList, setCategoryList] = useState([]);
  const [formInfo, setformInfo] = useState({});
  const [content, setContent] = useState("");
  // const [newsInfo, setnewsInfo] = useState([])
  const NewsForm = useRef(null);
  const navigate = useNavigate()
  const params = useParams()
  const handlePrevious = () => {
    setcurrent(current - 1);
  };

  useEffect(() => {
    // console.log()
    axios.get(`http://localhost:5000/news/${params.id}?_expand=category&_expand=role`).then(res => {
        // setnewsInfo(res.data)
        let {title,categoryId,content} = res.data
            NewsForm.current.setFieldsValue({
                title,
                categoryId
            })
            setContent(content)

    })
}, [params.id])

  const handleNext = () => {
    if (current === 0) {
      NewsForm.current
        .validateFields()
        .then((res) => {
          // console.log(res);
          setformInfo(res);
          setcurrent(current + 1);
        })
        .catch((error) => {
          console.log(error);
        });
    } else {
      if (content === "" || content.trim() === "<p></p>") {
        message.error("新闻内容不能为空");
      } else {
        setcurrent(current + 1);
      }
    }
  };

  useEffect(() => {
    axios.get("http://localhost:5000/categories").then((res) => {
      setCategoryList(res.data);
     
    });
  }, []);

  const handleSave = (auditState) => {
    axios
      .patch(`http://localhost:5000/news/${params.id}`, {
        ...formInfo,
        content: content,
        auditState: auditState,
        // "publishTime": 0
      })
      .then((res) => {
        navigate(
          auditState === 0 ? "/news-manage/draft" : "/audit-manage/list"
        );

        notification.info({
          message: `通知`,
          description: `您可以到${
            auditState === 0 ? "草稿箱" : "审核列表"
          }中查看您的新闻`,
          placement: "bottomRight",
        });
      });
  };

  return (
    <>
      <PageHeader
        className="site-page-header"
        title="更新新闻"
        subTitle="This is a subtitle"
        onBack={()=>{navigate(-1)}}
      />

      <Steps current={current}>
        <Step title="基本信息" description="新闻标题，新闻分类" />
        <Step title="新闻内容" description="新闻主体内容" />
        <Step title="新闻提交" description="保存草稿或者提交审核" />
      </Steps>

      <div
        className={current === 0 ? "" : "active"}
        style={{ margin: "50px 0" }}
      >
        <Form
          name="basic"
          labelCol={{ span: 2 }}
          wrapperCol={{ span: 22 }}
          initialValues={{ remember: true }}
          autoComplete="off"
          ref={NewsForm}
        >
          <Form.Item
            label="新闻标题"
            name="title"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="新闻分类"
            name="categoryId"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Select>
              {categoryList.map((item) => (
                <Option value={item.id} key={item.id}>{item.value}</Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </div>
      <div className={current === 1 ? "" : "active"}>
        <NewsEditor
          getContent={(value) => {
            // console.log(value);
            setContent(value);
          }} content={content}
        />
      </div>
      <div className={current === 2 ? "" : "active"}></div>

      {current > 0 && (
        <Button
          onClick={handlePrevious}
          type="primary"
          style={{ margin: "10px" }}
        >
          上一步
        </Button>
      )}
      {current < 2 && (
        <Button onClick={handleNext} type="primary" style={{ margin: "10px" }}>
          下一步
        </Button>
      )}
      {current === 2 && (
        <div>
          <Button type="primary" onClick={() => handleSave(0)}>
            保存草稿箱
          </Button>
          <Button danger onClick={() => handleSave(1)}>
            提交审核
          </Button>
        </div>
      )}
    </>
  );
}
